﻿
using System;
using System.Collections.Generic;
using System.Linq;
using fc2editor.DataModel;
using fc2editor.Lua;
namespace fc2editor.Services
{
    public class AircraftService : IAircraftService
    {
        public AircraftService(IFileService fileService, IWeaponService weaponService)
        {
            this.weaponService = weaponService;

            cache = LoadAircrafts(fileService);
        }

        #region IAircraftService Members

        public Aircraft[] GetAircrafts()
        {
            return cache.Values.ToArray();
        }

        public Aircraft GetAircraftByID(Guid id)
        {
            Aircraft result = null;
            cache.TryGetValue(id, out result);
            return result;
        }

        public Aircraft ReloadAircraftByID(Guid id)
        {
            if (!cache.ContainsKey(id))
                return null;

            var aircraft = cache[id];
            var parser = new AircraftParser(weaponService);
            var freshAircraft = parser.Parse(aircraft.FileName, aircraft.Type);
            if (freshAircraft != null)
            {
                cache[id] = freshAircraft;
                return freshAircraft;
            }

            return null;
        }

        #endregion

        private Dictionary<Guid, Aircraft> LoadAircrafts(IFileService fileService)
        {
            var planes = LoadPlanes(fileService);
            var helicopters = LoadHelicopters(fileService);
            var allAircrafts = planes.Union(helicopters);

            return allAircrafts.ToDictionary(p => p.ID, p => p);
        }

        private IEnumerable<Aircraft> LoadPlanes(IFileService fileService)
        {
            var planeFiles = fileService.GetPlanesFileNames();
            return LoadAircraftsImpl(planeFiles, AircraftType.Plane);
        }

        private IEnumerable<Aircraft> LoadHelicopters(IFileService fileService)
        {
            var helicopterFiles = fileService.GetHelicopersFileNames();
            return LoadAircraftsImpl(helicopterFiles, AircraftType.Helicopter);
        }

        private IEnumerable<Aircraft> LoadAircraftsImpl(IEnumerable<string> fileNames, AircraftType aType)
        {
            var result = new List<Aircraft>();

            var parser = new AircraftParser(weaponService);
            foreach (var p in fileNames)
            {
                var plane = parser.Parse(p, aType);
                if (plane != null)
                {
                    result.Add(plane);
                }
            }

            return result;
        }

        private Dictionary<Guid, Aircraft> cache;
        private IWeaponService weaponService;
    }
}
